package com.test.textGame.mq;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.test.textGame.algorithm.TopK;
import com.test.textGame.enums.MqLogTypeEnum;
import com.test.textGame.service.MqFailLogService;
import com.test.textGame.service.Top10Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@Component
public class RabbitMqSlaverConsumer {

    @Autowired
    private MqFailLogService mqFailLogService;
    @Autowired
    private Top10Service top10Service;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = "${top10.sort.group1.queue}"),
                    exchange = @Exchange(value = "${top10.sort.group1.exchange}", type = ExchangeTypes.TOPIC),
                    key = "${top10.sort.group1.routekey}")
    }, containerFactory = "rabbitListenerContainerFactory")
    public void process(String data, Message message, Channel channel) throws IOException {
        try {
            if (StringUtils.isEmpty(data)) {
                log.error("group1 master开始计算, 信息为空");
                return;
            }
            TopK.Node node = JSONObject.parseObject(data, TopK.Node.class);
            log.info("group1 master开始计算");
            synchronized (RabbitMqSlaverConsumer.class) {
                top10Service.consumeSlaverMsg(node.player, node.score);
            }
        } catch (Exception e) {
            log.error(String.format("group1 master开始计算MQ数据接收异常:%s", data), e);
            mqFailLogService.saveLog(MqLogTypeEnum.GAME_LEADER_CONSUME_FAIL, data);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
